import { Component, OnInit, ViewChild, TemplateRef, ChangeDetectorRef } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { SocialService } from '@delon/auth';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { STData, STComponent, STColumn, STChange } from '@delon/abc';
import { NzMessageService, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-routes-attributes',
  styleUrls: ['./attributes.component.less'],
  templateUrl: './attributes.component.html',
  providers: [SocialService],
})
export class RoutesAttributesComponent implements OnInit {


  data: any[] = []; // table 数据源
  url: string; // 新增、修改、删除 地址
  form: FormGroup; // 新增、修改表单数据
  loading = false; // 表单遮蔽层
  selectedRows: STData[] = []; //   checkbox选中的行
  @ViewChild('modalContent', { static: true })
  modalContent: TemplateRef<{}>;  // 新增、修改模板
  expandForm = false; // 查询框的收缩、展开
  query: any = {
    pageNo: 1, // 页码
    pageSize: 10, // 页数
    orderBy: '', // 排序
    condition: {} // 条件
  }; // 查询条件

  page: any = {
    total: 0, //  默认0
    range: [0, 10], // 范围
    pageParam: {
      front: false, // 是否前端控制分页
      showSize: true, // 是否显示分页器中改变页数
      showQuickJumper: true, // 是否显示分页器中快速跳转
      indexReset: false,
      total: '共有{{total}}条数据，当前{{range[0]}}-{{range[1]}}行',
    }  // STPage
  } // table 分页器


  @ViewChild('st', { static: true })
  st: STComponent;
  columns: STColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    {
      title: '行号', type: 'no', width: '60px',
    },
    {
      title: '名称', index: 'name',
      sort: {
        compare: (a, b) => a.name.localeCompare(b.name)
      },
      filter: {
        type: 'keyword',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
      }
    },
    {
      title: '备注', index: 'remark',
      sort: {
        compare: (a, b) => a.remark.localeCompare(b.remark)
      },
      filter: {
        type: 'keyword',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
      }
    },
    // {
    //   title: '更新时间', index: 'updateDate', type: 'date',
    //   sort: {
    //     compare: (a, b) => a.serialNum.localeCompare(b.serialNum)
    //   },
    //   filter: {
    //     type: 'keyword',
    //     fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
    //   }
    // },
    {
      title: '操作',
      buttons: [
        {
          text: '修改',
          click: (item: any) => this.update(item),
        },
        {
          text: '删除',
          click: (item: any) => this.deleteConfirm(item),
        },
      ],
    },
  ];


  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private cdr: ChangeDetectorRef,
    private fb: FormBuilder,
    private notification: NzNotificationService
  ) { }

  ngOnInit() {
    // 表单初始化
    this.form = this.fb.group({
      attributesId: [null],
      name: [null, [Validators.required]],
      remark: [null],
    });

    this.getData();
  }

  /**
   * 获取列表数据
   */
  getData() {
    this.loading = true;
    this.http.post("/zfy/Attributes/attributes/getByPage", this.query).subscribe(res => {
      this.loading = false;
      if (res.code === 0) {
        this.changeData(res.data)
        return;
      }
      this.notification.error(res.message + "！！！错误！", ``);
    })
  }

  /**
   * 查询数据
   */
  serchData() {
    // 清空分页参数
    this.query.pageNo = 1;
    this.getData();
  }
  /**
   * 当获取到数据后对数据进行拆分保存
   * @param data 数据源
   */
  changeData(data: any) {
    // for (let i = 0, no = data.startRow; no < data.endRow; i++ , no++) {
    //   data.list[i]['no'] = no;
    // } 
    this.data = data.list;
    this.selectedRows = [];
    this.page.total = data.total;
    this.page.range = [data.startRow, data.endRow];
    this.cdr.detectChanges();
  }

  /**
   * 新增（单条记录）
   * @param tpl 模板
   */
  add() {
    this.url = '/zfy/Attributes/attributes/save';
    this.form.reset();
    this.modalSrv.create({
      nzTitle: '新建商品属性',
      nzContent: this.modalContent,
      nzOnOk: () => new Promise((resolve) => {
        this.addItem().subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getData();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   * 修改（单条记录） 
   * @param item 行数据
   */
  update(item: any) {
    this.url = '/zfy/Attributes/attributes/update';
    this.form.reset();
    for (const key of Object.keys(this.form.value)) {
      this.form.controls[key].setValue(item[key]);
    }
    this.modalSrv.create({
      nzTitle: '修改商品属性',
      nzContent: this.modalContent,
      nzOnOk: () => new Promise((resolve) => {
        this.updateItem().subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getData();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   * 新增保存记录（单条） 
   */
  addItem(): Observable<any> {
    return new Observable<any>(ob => {
      this.http.post(this.url, this.form.value).subscribe(res => {
        ob.next(res);
      })
    })
  }

  /**
   * 修改保存记录（单条） 
   */
  updateItem(): Observable<any> {
    return new Observable<any>(ob => {
      this.http.put(this.url, this.form.value).subscribe(res => {
        ob.next(res);
      })
    })
  }

  /**
   * 删除提示框
   * @param item 行数据
   */
  deleteConfirm(item: any) {
    this.url = '/zfy/Attributes/attributes/delete?id=' + item.attributesId;
    this.modalSrv.confirm({
      nzTitle: '提示',
      nzContent: '确认删除（单条）记录？',
      nzOnOk: () => new Promise(resolve => {
        this.deleteItem().subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getData();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   * 删除记录（单条）
   * @param item 行数据
   */
  deleteItem(): Observable<any> {
    return new Observable(ob => {
      this.http.delete(this.url).subscribe(res => {
        ob.next(res);
      })
    })
  }

  /**
   * 批量删除提示框
   */
  batchDeleteConfirm() {
    if (this.selectedRows.length <= 0) {
      this.msg.error('未选中数据');
      return;
    }

    const array = new Array();
    for (const item of this.selectedRows) {
      array.push(item.attributesId)
    }
    this.url = '/zfy/Attributes/attributes/batchDelete?ids=' + array.join(',');
    this.modalSrv.confirm({
      nzTitle: '提示',
      nzContent: '确认删除（选中行）记录？',
      nzOnOk: () => new Promise(resolve => {
        this.batchDeleteItems().subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message + '共删除' + res.data + '条记录');
            this.getData();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   *  批量删除
   */
  batchDeleteItems(): Observable<any> {
    return new Observable(ob => {
      this.http.delete(this.url).subscribe(res => {
        ob.next(res);
      })
    })
  }

  /**
   * tbale 选中行、分页改变 
   * @param e 数据
   */
  stChange(e: STChange) {
    console.log(e);
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox;
        break;
      case 'pi':
        this.query.pageNo = e.pi;
        this.query.pageSize = e.ps;
        this.getData();
        break;
      case 'ps':
        this.query.pageNo = e.pi;
        this.query.pageSize = e.ps;
        this.getData();
        break;
    }
  }


  reset() {
    // wait form reset updated finished
    setTimeout(() => this.getData());
  }

}
